<template>
  <div class="statistics-container">
    <div class="page-header">
      <h2>数据统计</h2>
      <div class="date-range">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          @change="handleDateChange"
        />
        <el-button type="primary" @click="handleRefresh">
          <el-icon><Refresh /></el-icon>
          刷新数据
        </el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon user-icon">
                <el-icon><User /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ stats.totalUsers }}</div>
                <div class="stat-label">总用户数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon question-icon">
                <el-icon><Document /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ stats.totalQuestions }}</div>
                <div class="stat-label">题目总数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon paper-icon">
                <el-icon><Notebook /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ stats.totalPapers }}</div>
                <div class="stat-label">试卷总数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon exam-icon">
                <el-icon><Trophy /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ stats.totalExams }}</div>
                <div class="stat-label">考试次数</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 图表区域 -->
    <div class="charts-section">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-card>
            <template #header>
              <span>用户注册趋势</span>
            </template>
            <div ref="userTrendChart" class="chart-container"></div>
          </el-card>
        </el-col>
        
        <el-col :span="12">
          <el-card>
            <template #header>
              <span>考试完成情况</span>
            </template>
            <div ref="examStatusChart" class="chart-container"></div>
          </el-card>
        </el-col>
      </el-row>
      
      <el-row :gutter="20" style="margin-top: 20px;">
        <el-col :span="12">
          <el-card>
            <template #header>
              <span>题目类型分布</span>
            </template>
            <div ref="questionTypeChart" class="chart-container"></div>
          </el-card>
        </el-col>
        
        <el-col :span="12">
          <el-card>
            <template #header>
              <span>成绩分布</span>
            </template>
            <div ref="scoreDistributionChart" class="chart-container"></div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <template #header>
        <span>最近考试记录</span>
      </template>
      
      <el-table :data="recentExams" v-loading="loading">
        <el-table-column prop="studentName" label="学生姓名" />
        <el-table-column prop="paperName" label="试卷名称" />
        <el-table-column prop="score" label="得分">
          <template #default="{ row }">
            <span :class="getScoreClass(row.score)">{{ row.score }}分</span>
          </template>
        </el-table-column>
        <el-table-column prop="duration" label="用时(分钟)" />
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">{{ getStatusText(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="submitTime" label="提交时间" />
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { User, Document, Notebook, Trophy, Refresh } from '@element-plus/icons-vue'

const loading = ref(false)
const dateRange = ref([])

// 统计数据
const stats = reactive({
  totalUsers: 0,
  totalQuestions: 0,
  totalPapers: 0,
  totalExams: 0
})

// 最近考试记录
const recentExams = ref([])

// 图表引用
const userTrendChart = ref()
const examStatusChart = ref()
const questionTypeChart = ref()
const scoreDistributionChart = ref()

// 获取统计数据
const fetchStatistics = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 模拟统计数据
    Object.assign(stats, {
      totalUsers: 1250,
      totalQuestions: 3680,
      totalPapers: 156,
      totalExams: 2340
    })
    
    // 模拟最近考试记录
    recentExams.value = [
      {
        id: 1,
        studentName: '张三',
        paperName: '数学期末考试',
        score: 85,
        duration: 95,
        status: 'completed',
        submitTime: '2024-01-15 14:30:00'
      },
      {
        id: 2,
        studentName: '李四',
        paperName: '英语四级模拟',
        score: 72,
        duration: 120,
        status: 'completed',
        submitTime: '2024-01-15 13:45:00'
      },
      {
        id: 3,
        studentName: '王五',
        paperName: '计算机基础',
        score: 0,
        duration: 0,
        status: 'timeout',
        submitTime: '2024-01-15 12:00:00'
      }
    ]
  } catch (error) {
    ElMessage.error('获取统计数据失败')
  } finally {
    loading.value = false
  }
}

// 初始化图表
const initCharts = async () => {
  await nextTick()
  
  // 这里应该使用真实的图表库如 ECharts
  // 为了演示，我们只是添加一些占位内容
  if (userTrendChart.value) {
    userTrendChart.value.innerHTML = '<div style="height: 300px; display: flex; align-items: center; justify-content: center; color: #999;">用户注册趋势图表</div>'
  }
  
  if (examStatusChart.value) {
    examStatusChart.value.innerHTML = '<div style="height: 300px; display: flex; align-items: center; justify-content: center; color: #999;">考试完成情况图表</div>'
  }
  
  if (questionTypeChart.value) {
    questionTypeChart.value.innerHTML = '<div style="height: 300px; display: flex; align-items: center; justify-content: center; color: #999;">题目类型分布图表</div>'
  }
  
  if (scoreDistributionChart.value) {
    scoreDistributionChart.value.innerHTML = '<div style="height: 300px; display: flex; align-items: center; justify-content: center; color: #999;">成绩分布图表</div>'
  }
}

// 日期范围改变
const handleDateChange = (dates) => {
  console.log('日期范围改变:', dates)
  fetchStatistics()
}

// 刷新数据
const handleRefresh = () => {
  fetchStatistics()
  initCharts()
  ElMessage.success('数据已刷新')
}

// 获取分数样式
const getScoreClass = (score) => {
  if (score >= 90) return 'score-excellent'
  if (score >= 80) return 'score-good'
  if (score >= 60) return 'score-pass'
  return 'score-fail'
}

// 获取状态类型
const getStatusType = (status) => {
  const types = {
    completed: 'success',
    timeout: 'warning',
    abandoned: 'danger'
  }
  return types[status] || ''
}

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    completed: '已完成',
    timeout: '超时',
    abandoned: '放弃'
  }
  return texts[status] || '未知'
}

onMounted(() => {
  // 设置默认日期范围为最近30天
  const end = new Date()
  const start = new Date()
  start.setDate(start.getDate() - 30)
  dateRange.value = [start.toISOString().split('T')[0], end.toISOString().split('T')[0]]
  
  fetchStatistics()
  initCharts()
})
</script>

<style scoped>
.statistics-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.date-range {
  display: flex;
  align-items: center;
  gap: 12px;
}

.stats-cards {
  margin-bottom: 20px;
}

.stat-card {
  height: 120px;
}

.stat-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  font-size: 24px;
  color: white;
}

.user-icon {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.question-icon {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.paper-icon {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.exam-icon {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 32px;
  font-weight: bold;
  color: #303133;
  line-height: 1;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-top: 4px;
}

.charts-section {
  margin-bottom: 20px;
}

.chart-container {
  height: 300px;
  background: #fafafa;
  border-radius: 4px;
}

.table-card {
  margin-top: 20px;
}

.score-excellent {
  color: #67c23a;
  font-weight: bold;
}

.score-good {
  color: #409eff;
  font-weight: bold;
}

.score-pass {
  color: #e6a23c;
  font-weight: bold;
}

.score-fail {
  color: #f56c6c;
  font-weight: bold;
}
</style>